// axios 封装
function createClient(baseURL) {
    const axiosInstance = axios.create({
        baseURL: baseURL, timeout: 5000, // 设置请求超时时间
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })

    // 通用 GET 请求封装
    const get = async (url) => {
        try {
            const response = await axiosInstance.get(url)
            return response.data
        } catch (error) {
            console.error('GET 请求失败:', error)
            throw error
        }
    }

    // 通用 POST 请求封装
    const post = async (url, data) => {
        try {
            const response = await axiosInstance.post(url, new URLSearchParams(data))
            return response.data
        } catch (error) {
            console.error('POST 请求失败:', error)
            throw error
        }
    }

    return {
        get, post
    }
}

// 用户管理客户端
const userClient = (() => {
    const client = createClient('/api')

    const listUsers = async () => await client.get('/user?action=list')

    const updateUser = async (user) => {
        const params = {
            username: user.username, password: user.password, attUrl: user.avatarUrl
        }
        return await client.post('/user?action=update', params)
    }

    const deleteUser = async (username) => {
        const params = {
            username: username
        }
        return await client.post('/user?action=delete', params)
    }

    const getUser = async (username) => {
        const params = {
            username: username
        }
        return await client.post('/user?action=getUser', params)
    }

    return {
        listUsers, updateUser, deleteUser, getUser
    }
})()

// 页面逻辑
$(document).ready(async function () {
    const userTableBody = $('#userTableBody')

    // 加载用户列表
    const loadUsers = async () => {
        try {
            const data = await userClient.listUsers()
            if (data.code === 1) {
                userTableBody.empty()
                $.each(data.data, function (_, user) {
                    userTableBody.append(`<tr>
                <td><img src="${user.avatarUrl}" alt="avatar" class="w-12 h-12 rounded-full"></td>
                <td>${user.username}</td>
                <td>${user.role}</td>
                <td>
                    <button class="btn btn-sm btn-info mr-2 edit-btn" data-username='${user.username}'>编辑</button>
                    <button class="btn btn-sm btn-danger delete-btn" data-username="${user.username}">删除</button>
                </td>
            </tr>`)
                })
            } else {
                alert('加载用户列表失败: ' + data.msg)
            }
        } catch (error) {
            alert('加载用户失败，请重试')
        }
    }

    // 打开模态框
    const openModal = (user) => {
        $('#username').val(user.username)
        $('#password').val(user.password || '')
        $('#avatarUrl').val(user.avatarUrl || '')
        $('#userModal').addClass('modal-open')
    }

    // 关闭模态框
    const closeModal = () => {
        $('#userModal').removeClass('modal-open')
    }

    // 手动取消模态框
    $('#cancelSubmit').on('click', function() {
        closeModal()
    })

    // 编辑用户
    userTableBody.on('click', '.edit-btn', function () {
        const username = $(this).data('username')
        userClient.getUser(username).then(data => {
            if (data.code === 1) {
                openModal(data.data)
            } else {
                alert('获取用户信息失败: ' + data.msg)
            }
        }).catch(error => {
            alert('获取用户信息失败，请重试')
        })
    })

    // 删除用户
    userTableBody.on('click', '.delete-btn', async function () {
        const username = $(this).data('username')
        if (confirm('确定要删除该用户吗？')) {
            try {
                const data = await userClient.deleteUser(username)
                if (data.code === 1) {
                    alert('删除成功')
                    await loadUsers()
                } else {
                    alert('删除失败: ' + data.msg)
                }
            } catch (error) {
                alert('删除失败，请重试')
            }
        }
    })

    // 保存用户
    $('#userForm').on('submit', async function (event) {
        event.preventDefault()
        const user = {
            username: $('#username').val(),
            password: $('#password').val(),
            avatarUrl: $('#avatarUrl').val(),
            role: $('#role').val()
        }

        try {
            const data = await userClient.updateUser(user)
            if (data.code === 1) {
                alert('保存成功')
                closeModal()
                await loadUsers()
            } else {
                alert('保存失败: ' + data.msg)
            }
        } catch (error) {
            alert('保存失败，请重试')
        }
    })

    // 初始化页面
    await loadUsers()
})